import urllib.request
import urllib.parse
import json


def create_request(pageIndex):
    base_url = ('https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname')
    data = {
        "cname": "成都",
        "pid": "",
        "pageIndex": pageIndex,
        "pageSize": "10"
    }
    data = urllib.parse.urlencode(data).encode("utf-8")

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
    }
    request = urllib.request.Request(url=base_url, data=data, headers=headers)
    return request


def fetch_page(requests):
    response = urllib.request.urlopen(requests)
    data = json.loads(response.read().decode('utf-8'))
    return data


def download_page(page, data):
    with open('kfc_page' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        json_str = json.dumps(data, ensure_ascii=False, indent=4)
        fp.write(json_str)
        print("kfc目标：" + str(page) + '，已经下载完毕！')


# 程序入口
if __name__ == '__main__':
    start_page = int(input("请输入起始的页码："))
    end_page = int(input("请输入结束的页码："))

    for pageIndex in range(start_page, end_page + 1):
        # 定制每一页的请求对象（url不同）
        requests = create_request(pageIndex)
        # 获取数据
        data = fetch_page(requests)
        # 保存数据
        download_page(pageIndex, data)
